import util from './util'
import mqtt from 'mqtt'  // "mqtt": "^4.3.7",
import { ElNotification } from 'element-plus'
import axios from '@/axios/axios'

const MQTT_URL = [
  'wss://www.androidgmt.com:8081/mqtt',
  'ws://www.androidgmt.com:8082/mqtt',
  'wss://192.168.6.95:8081/mqtt',
  'ws://192.168.6.95:8082/mqtt'
]
var client = null
var qos = 0
// 登录连接
function login(user,password,cb) {
  const connectUrl = MQTT_URL[0]
  const options = {
    clean: true,
    connectTimeout: 4000,
    clientId: 'AndroidGmt@'+user+'|'+user,
    username: 'AndroidGmt@'+user,
    password: password,
    // ssl: true,
    // protocolVersion: 5,
    // rejectUnauthorized: true,
  }
  // console.log('url:',connectUrl)
  // console.log('clientId:',options.clientId)
  // console.log('username:',options.username)
  // console.log('password:',options.password)
  try {
    client = mqtt.connect(connectUrl, options);
  } catch (e) {
    // console.log(e)
    cb('fail',e)
    ElNotification({
      type: 'error',
      title: '服务器连接失败',
      message: e
    })
  }
  client.on('connect', function(r) {
    // console.log(r)
    // console.log(client)
    r.clientId = options.clientId
    r.username = options.username
    r.tel = user
    cb('success',r)
    // getPowers(options.clientId,options.username)
  }).on('reconnect', function(e) {
  //console.log('正在重连...'+new Date(), e)
  //console.log(client)
    if (showNotifaction) {
      ElNotification({
        type: 'error',
        title: '正在重新连接服务器……',
        duration: 1500,
      })
      showNotifaction = false
      setTimeout(() => {
        showNotifaction = true
      }, 1500);
    }
    cb('fail','reconnect')
  }).on('error', function(e) {
  //console.log('连接失败...'+new Date(), e)
    let err = e
    if (e.toString().indexOf('Identifier rejected')>=0) {
      close()
      err = '身份验证失败，用户名或密码错误'
    }
    ElNotification({
      type: 'error',
      title: '登录失败',
      message: err,
      duration: 2000,
    })
    cb('fail',err)
  }).on('close', function(e) {
  //console.log('连接断开'+new Date(),e)
    close(true)
    cb('fail',e)
  }).on('message', function(topic, message) {
    // console.log('%c收到'+topic+'消息：'+message.toString(),'color: green')
    cb(topic,message.toString())
  })
}
// 断开连接
function close(showTip=false) {
//console.log('close client',client)
  if (client == null) return
  client.end(false, {}, (e)=>{
  //console.log('onEnd','主动断开 '+new Date()+e)
    client = null
    if (showTip) {
      let d= 2000
      ElNotification({
        type: 'error',
        title: '服务器连接失败',
        // message: '正在重新连接服务器……',
        duration: d,
      })
      // setTimeout(() => {
      //   window.location.href = (axios.rootUrl);
      // }, d);
    }
  })
}
// 订阅
function subscribe(topic) {
  client.subscribe(topic,{ qos },(err) => {
  //console.log(err || topic+'订阅成功')
    if (err) {
      ElNotification({
        type: 'error',
        title: topic+'订阅失败',
        message: err
      })
    } else {
      publish(test_topic+'testConnection','mqtt消息发布测试')
    }
  })
}
// 取消订阅
function unsubscribe(topic) {
  client.unsubscribe(topic,(err) => {
  //console.log(err || topic+'订阅取消成功')
    if (err) {
      ElNotification({
        type: 'error',
        title: topic+'订阅取消失败',
        message: err
      })
    }
  })
}
// 发布
function publish(topic,msg) {
  let err = ''
  let result = false
  if (util.isNull(topic)) err = '发布主题不能为空'
  if (util.isNull(msg)) err = '发布消息不能为空'
  if (util.isNull(err)) {
    try {
      client.publish(topic,msg,(err) => {
        //console.log(err || topic+'发布成功')
        if (err) {
          ElNotification({
            type: 'error',
            title: topic+'MQTT信息发布失败',
            message: err
          })
        } else {
          result = true
        }
      })
    } catch (error) {
    //console.log(error)
      logout('登录身份已失效，请重新登录');
      // ElNotification({
      //   type: 'warning',
      //   duration: 1500,
      //   title: 'MQTT信息发布失败',
      //   message: error
      // })
    } 
  } else {
    ElNotification({
      type: 'warning',
      duration: 1500,
      title: 'MQTT信息发布失败',
      message: err
    })
  }
  return result
}
// 信息监听
let showNotifaction = true
function onMsg(cb) {
  try {
    client.on('message', function(topic, message) {
      // console.log('%c收到'+topic+'消息：'+message.toString(),'color: green')
      let r = JSON.parse(message)
      cb(topic,message.toString())
      if (r.msgType < 0 || r.data.returnCode != 10000) {
        let msg = r.data.message
      //console.log(msg)
        if (msg.indexOf('dup key') >=0) msg = '已存在当前信息，不可重复录入'
        if (msg.indexOf('密码错误') >=0) msg = '原密码不正确'
        if (showNotifaction) {
          ElNotification({
            type: 'warning',
            duration: 1500,
            // title: '失败',
            message: msg
          })
          showNotifaction = false
          setTimeout(() => {
            showNotifaction = true
          }, 1500);
        }
      }
    })
  } catch (error) {
  //console.log(error) 
    logout('登录身份已失效，请重新登录');
  }
}
// 用户信息已过期，重新登录
function logout(err) {
  close();
  let d = 0
  if (!util.isNull(err)) {  
    ElNotification({
      type: 'error',
      title: '退出登录',
      message: err
    })
    d = 2000
  }
  setTimeout(() => {
    window.location.href = (axios.rootUrl);
  }, d);
}
// 常用主题
const TOPIC_REQ = 'AndroidPlatService/Execute/'

export default{
  login,close,subscribe,unsubscribe,publish,onMsg,logout,
  TOPIC_REQ,
}

// 查看权限
function getPowers(cid,user) {
  let msgCode = 57
  let topic = TOPIC_REQ+msgCode
  let g = {}
  g.msgType = msgCode
  g.clientId = cid
  g.userName = user
  let m = {}
  m.indexPage = 1
  m.pageSize = 1000
  g.message = m
  publish(topic,JSON.stringify(g))
}